package org.example.algorithm.binarytree;

import org.example.algorithm.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 递归+非递归方式后序遍历二叉树
 */

public class PostorderTraversalSolution {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(3);
        treeNode.left = new TreeNode(5);
        treeNode.right = new TreeNode(7);
        treeNode.left.left = new TreeNode(9);
        treeNode.left.right = new TreeNode(8);
        treeNode.left.left.left = new TreeNode(2);
        List<Integer> result = postorderTraversal(treeNode);
        System.out.println(result);
    }

    public static List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode visit = null;
        while (!stack.isEmpty() || cur != null) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode node = stack.peek();
            if (node.right == null || visit == node.right) {
                res.add(node.val);
                stack.pop();
                visit = node;
            } else {
                cur = node.right;
            }
        }
        return res;
    }

    public static List<Integer> postorderTraversal2(TreeNode treeNode) {
        List<Integer> result = new ArrayList<>();
        doPostorderTraversal(treeNode, result);
        return result;
    }

    private static void doPostorderTraversal(TreeNode treeNode, List<Integer> result) {
        if (treeNode == null) {
            return;
        }
        doPostorderTraversal(treeNode.left, result);
        doPostorderTraversal(treeNode.right, result);
        result.add(treeNode.val);
    }
}
